package com.xiaobai.config;

import com.xiaobai.common.ServiceResponse;
import com.xiaobai.exception.LoginException;
import com.xiaobai.exception.InterceptorException;
import com.xiaobai.exception.RequestException;
import com.xiaobai.exception.UpdatePasswordException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    // 登录时的正常错误
    @ExceptionHandler(LoginException.class)
    @ResponseStatus(HttpStatus.NOT_IMPLEMENTED)//未实现501
    public ServiceResponse runTimeException(LoginException loginException) {
        log.error(loginException.getMessage());
        return ServiceResponse.failV2(loginException.getMessage());
    }

    @ExceptionHandler(RequestException.class)
    public ServiceResponse requestException(RequestException requestException) {
        return ServiceResponse.fail(requestException.getMessage());
    }

    @ExceptionHandler(UpdatePasswordException.class)
    @ResponseStatus(HttpStatus.FORBIDDEN)//403
    public ServiceResponse errorResponse0(UpdatePasswordException e){
        System.out.println("捕获401异常:"+e.getMessage());
        return ServiceResponse.createByErrorMsg(e.getMessage());
    }

    @ExceptionHandler(InterceptorException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)//401
    public ServiceResponse errorResponse1(InterceptorException e){
        System.out.println("捕获401异常:"+e.getMessage());
        return ServiceResponse.createByError();
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.NOT_IMPLEMENTED)//未实现501
    public ServiceResponse errorResponse2(Exception e){
        System.out.println("捕获内部异常:"+e.getMessage());
        e.printStackTrace();
        return ServiceResponse.createByError();
    }

}
